package com.laomuji.android.mvvm.http.interceptor

import com.laomuji.android.mvvm.http.encrypt.EncryptFactory
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 标准拦截器
 * @author laomuji666
 * @since 2024/2/20
 */
class StandardInterceptor(tag: String) : Interceptor {
    val headerInterceptor: HeaderInterceptor = HeaderInterceptor()
    private val logInterceptor: LogInterceptor = LogInterceptor(tag)

    override fun intercept(chain: Interceptor.Chain): Response {
        var builder = chain.request().newBuilder()

        //拦截请求,添加请求头
        builder = headerInterceptor.addRequestHeader(builder.build())

        //拦截请求,加密
        val encryptHeader = builder.build().header(EncryptFactory.EncryptKey.ENCRYPT_HEADER_KEY)
        if (encryptHeader != null) {
            builder = EncryptFactory.encrypt(builder.build(), encryptHeader)
        }

        //拦截请求,打印日志
        logInterceptor.requestLog(builder.build())

        //发起请求,等待响应
        val response = chain.proceed(builder.build())

        //响应拦截,打印日志
        logInterceptor.responseLog(response)

        return response
    }
}